<template>
  <div class="app-container" id="user">
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="店铺名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="店铺封面">
        <el-upload class="cover-uploader" action="http://www.jiatingyigou.com:7001/upload/img" :show-file-list="false" :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload">
          <img v-if="form.avatar" :src="form.avatar" class="cover">
          <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
      </el-form-item>
      <el-form-item label="店铺位置">
        <el-button @click="dialogPoiVisible = true">{{address}}</el-button>
      </el-form-item>
      <el-dialog title="选择地址" :visible.sync="dialogPoiVisible" top="15vh">
        <div class="amap-page-container">
          <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
          <el-amap vid="amap" :center="center" :zoom="zoom" :plugin="plugin" class="amap-demo" :events="events">
            <el-amap-marker :position="MakerPosition"></el-amap-marker>
          </el-amap>
          <div class="toolbar">
            <br /> 地址：{{ address }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogPoiVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogPoiVisible = false">确 定</el-button>
      </span>
      </el-dialog>
      <el-form-item label="商品类别">
        <div class="block">
          <el-cascader expand-trigger="hover" :options="sellerType" v-model="goodsType" @change="handleChange">
          </el-cascader>
        </div>
      </el-form-item>

      <el-form-item label="其他设置">
        <el-tabs type="border-card">
          <el-tab-pane label="优惠管理">
            <p>添加店铺优惠：</p>
            <el-select v-model="couponType" placeholder="优惠类型">
              <el-option v-for="item in couponTypeOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
              </el-option>
            </el-select>
            <div class="p20" v-if="couponType==0">
              <span>满减规则： 满 </span>
              <el-input-number :controls="false" v-model="type0.price" class="w100"></el-input-number><span> 减 </span>
              <el-input-number :controls="false" v-model="type0.discount" class="w100"></el-input-number>
              <p>
                <el-button type="primary" @click="addType0">添加</el-button>
              </p>
            </div>
            <div class="p20" v-if="couponType==1">
              <span>折扣规则： 商品折扣为 </span>
              <el-input-number size="small" v-model="type1.discount" :min="1" :max="9"></el-input-number>
              <span> 折 </span>
              <p>
                <el-button type="primary" @click="addType1">添加</el-button>
              </p>
            </div>
            <div class="p20" v-if="couponType==2">
              <span>套餐搭配：</span>
              <el-input v-model="type2.description" class="w200" :maxlength="80"></el-input>
              <p>
                <span> 套餐总共： </span>
                <el-input-number :controls="false" v-model="type2.price" class="w100"></el-input-number><span> 元 </span>
              </p>
              <p>
                <el-button type="primary" @click="addType2">添加</el-button>
              </p>
            </div>
            <p>
              <span>已有优惠：</span>
              <el-tag v-for="(support,index) in form.supports" :key="support.description" :closable="true" @close="handleClose(support.id,index)"
                type="primary" style="margin-right:4px;">
                {{support.description}}
                </el-tag>
            </p>
          </el-tab-pane>
          <el-tab-pane label="商家信息" v-if="form.info.length>0">
            <p>
              消费类型 :
              <el-select v-model="form.sellType" placeholder="消费类型">
                <el-option v-for="item in deliveryOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </p>
            <p>详细地址：
              <el-input type="textarea" :rows="2" v-model="form.addressDetail" placeholder="请输入详细地址" class="w200"></el-input>
            </p>
            <p>营业时间：
              <el-input v-model="form.sellTime" placeholder="请输入营业时间" class="w200"></el-input>
            </p>
            <p>
              <el-checkbox v-model="invoice">提供发票</el-checkbox>
            </p>
            <p v-if="invoice">领取方式：
              <el-input type="textarea" :rows="2" v-model="form.invoiceText" placeholder="请输入发票领取方式" class="w200"></el-input>
            </p>
            <el-checkbox v-model="cancelTime">允许在规定时间内退款？</el-checkbox>
            <p v-if="cancelTime">
              截至退款时间 :
              <el-select v-model="form.cancelTime" placeholder="截至退款时间">
                <el-option v-for="item in limitTime" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </p>

            <p>
              <el-checkbox v-model="vip">提供商品送上门服务</el-checkbox>
              <p v-if="vip">最低配送价格：
                <el-input v-model="form.minPrice" placeholder="请输入起送价" class="w200"></el-input> 元
              </p>
              <p v-if="vip">最远配送距离：
                <el-input v-model="form.maxDistance" placeholder="请输入距离" class="w200"></el-input> 米
              </p>
              <p v-if="vip">大约配送时间：
                <el-input v-model="form.deliveryTime" placeholder="请输入距离" class="w200"></el-input> 分钟
              </p>
            </p>

          </el-tab-pane>
          <el-tab-pane label="商家口号与公告">
            <p>口号标语：
              <el-input type="textarea" :rows="2" v-model="form.description" placeholder="请输入口号或标语" class="w200"></el-input>
            </p>
            <p>商家公告：
              <el-input type="textarea" :rows="2" v-model="form.bulletin" placeholder="请输入公告" class="w200"></el-input>
            </p>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="店铺图片">
        <el-upload action="http://www.jiatingyigou.com:7001/upload/img" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove" :on-success="handleSuccess" :file-list="imgList">
          <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog v-model="dialogVisible" size="tiny">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveInfo">保存信息</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import { addSellerSupport, delSellerSupport, delSellerImg, addSellerImg, getSellerInfo, updateSellerInfo, updateSeller } from '@/api/seller'
  export default {
    data() {
      var self = this;
      return {
        cancelTime: false,
        goodsType: [],
        sellType: "",
        picVisible: false,
        imgList: [],
        typeName: "",
        dialogPoiVisible: false,
        dialogImageUrl: "",
        dialogVisible: false,
        couponType: null,
        avator: "",
        type0: {
          type: 1,
          price: 0,
          discount: 0,
          description: ""
        },
        type1: {
          type: 2,
          discount: 9,
          price: 0,
          description: ""
        },
        type2: {
          type: 3,
          description: "",
          discount: 9,
          price: 0
        },
        couponList: [],
        invoice: false,
        vip: false,
        couponTypeOptions: [
          {
            value: 0,
            label: "满减"
          },
          {
            value: 1,
            label: "折扣"
          },
          {
            value: 2,
            label: "套餐"
          }
        ],
        limitTime: [
          {
            value: "18:00",
            label: "18:00之前"
          },
          {
            value: "20:00",
            label: "20:00之前"
          },
          {
            value: "23:59",
            label: "23:59之前"
          }
        ],
        deliveryOptions: [
          {
            value: "商家配送",
            label: "商家配送"
          },
          {
            value: "到店消费",
            label: "到店消费"
          }
        ],
        sellerType: [
          {
            value: "hotel",
            label: "住宿",
            children: [
              {
                value: "flat",
                label: "公寓",
              },
              {
                value: "villa",
                label: "别墅",
              },
              {
                value: "hell",
                label: "山庄",
              },
              {
                value: "normal",
                label: "普通民宿",
              },
            ]
          },
          {
            value: "car",
            label: "出行",
            children: [
              {
                value: "bus",
                label: "大巴",
              },
              {
                value: "taxi",
                label: "出租汽车",
              },
              {
                value: "didi",
                label: "打车",
              }
            ]
          },
          {
            value: "goods",
            label: "玩乐物品",
            children: [
              {
                value: "party",
                label: "聚会",
              },
              {
                value: "picnic",
                label: "野餐/野餐",
              },
              {
                value: "car",
                label: "包车",
              },
              {
                value: "birthday",
                label: "生日",
              }
            ]
          },
          {
            value: "food",
            label: "美食",
            children: [
              {
                value: "beverage",
                label: "甜点饮品",
              },
              {
                value: "party",
                label: "聚餐团建",
              },
              {
                value: "breakfast",
                label: "早点",
              },
              {
                value: "midnight",
                label: "宵夜",
              },
              {
                value: "snack",
                label: "小吃快餐",
              },
              {
                value: "birthday",
                label: "生日蛋糕",
              },
              {
                value: "dish",
                label: "火锅",
              },
              {
                value: "buffet",
                label: "自助餐",
              },
              {
                value: "arrange",
                label: "日韩料理",
              },
              {
                value: "bbq",
                label: "烧烤烤肉",
              },
              {
                value: "fish",
                label: "香锅烤鱼",
              },
              {
                value: "drink",
                label: "咖啡酒吧",
              },
              {
                value: "gruel",
                label: "汤/粥/炖菜",
              },
              {
                value: "else",
                label: "其他美食",
              }
            ]
          },
          {
            value: "trip",
            label: "旅游",
            children: [
              {
                value: "drift",
                label: "激情漂流",
              },
              {
                value: "camp",
                label: "野营野餐",
              },
              {
                value: "visit",
                label: "参观展览",
              },
              {
                value: "farm",
                label: "农家乐",
              },
              {
                value: "villa",
                label: "别墅",
              },
              {
                value: "cs",
                label: "真人cs",
              },
              {
                value: "pleasure",
                label: "游乐场",
              },
              {
                value: "team",
                label: "跟团",
              }
            ]
          }
        ],
        form: {
          name: "",
          description: "",
          bulletin: "",
          pics: [],
          avatar: "",
          supports: [],
          info: [],
          sellTime: "",
          sellType: "",
          invoiceText: "",
          invoice: 0,
          cancelTime: "",
        },
        zoom: 12,
        center: [121.59996, 31.197646],
        address: "选择地址",
        describe: "",
        adcode: "",
        position: "",
        searchOption: {
          city: "全国",
          citylimit: true
        },
        addressInfo: {
          lat: "",
          lng: "",
          position: "",
          traffic: "",
          adcode: "",
          township: ""
        },
        plugin: [
          {
            pName: "Geolocation",
            events: {
              init(o) {
                o.getCurrentPosition((status, result) => {
                  console.log(result)
                  if (result && result.position) {
                    self.addressInfo.lng = result.position.lng;
                    self.addressInfo.lat = result.position.lat;
                    self.addressInfo.traffic = result.formattedAddress;
                    self.addressInfo.township = result.addressComponent.township;
                    self.address = result.formattedAddress;
                    self.form.info[1].info = self.address
                    self.addressInfo.adcode = result.addressComponent.adcode;
                    self.addressInfo.position =
                      result.addressComponent.city +
                      "-" +
                      result.addressComponent.district;
                  }
                });
              }
            }
          }
        ],
        events: {
          click(e) {
            let { lng, lat } = e.lnglat;
            self.addressInfo.lng = lng;
            self.addressInfo.lat = lat;
            self.MakerPosition = [e.lnglat.lng, e.lnglat.lat];
            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            });
            geocoder.getAddress([lng, lat], function (status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  self.addressInfo.traffic = result.regeocode.formattedAddress;
                  self.address = result.regeocode.formattedAddress;
                  self.addressInfo.township = result.regeocode.addressComponent.township;
                  self.form.info[1].info = self.address
                  self.addressInfo.adcode =
                    result.regeocode.addressComponent.adcode;
                  self.addressInfo.position =
                    result.regeocode.addressComponent.city +
                    "-" +
                    result.regeocode.addressComponent.district;
                  self.$nextTick();
                }
              }
            });
          }
        },
        MakerPosition: [121.59996, 31.197646],
        lng: 0,
        lat: 0,
        seller_id: 0
      };
    },
    created() {

      let sellerId = this.$route.query.sellerId
      this.seller_id = sellerId
      this.$nextTick(() => {
        getSellerInfo(sellerId).then((res) => {
          if (res.message == "ok") {
            this.form = res.seller
            this.form.pics = res.pics
            this.form.supports = res.supports
            this.addressInfo.adcode = this.form.city
            this.addressInfo.lat = this.form.lat
            this.addressInfo.lng = this.form.lng
            this.addressInfo.position = this.form.position
            this.addressInfo.traffic = this.form.traffic
            this.goodsType = [this.form.type, this.form.childType]
            if (res.infos[0]) {

              this.form.info = res.infos
            } else {
              this.form.info = [{ info: "", sell_id: res.seller.id, info_title: "消费类型", type: 1 },
              { info: "", sell_id: res.seller.id, info_title: "详细地址", type: 2 },
              { info: "", sell_id: res.seller.id, info_title: "营业时间", type: 3 }]
            }

            if (this.form.cancelTime) {
              this.cancelTime = true
            }


            if (this.form.sellType) {
              this.sellType = this.form.sellType
            }
            if (this.form.invoice == 1) {
              this.invoice = true
            }
            if (this.form.send == 1) {
              this.vip = true
            }
            this.imgList = this.form.pics
            this.address = this.form.position
          }
        })

      })

    },
    methods: {
      handleCoverSuccess(res, file) {
        this.avator = URL.createObjectURL(file.raw);
        this.form.avatar = "http://" + res.data.url;
        this.$message({
          message: '上传成功',
          type: 'success'
        });
      },
      beforeCoverUpload(file) {
        this.$message('正在上传...');
        const isJPG = file.type === "image/jpeg";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
      handleRemove(file, fileList) {

        this.imgList = this.form.pics.concat()
        this.$confirm("确定要删除图片？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          delSellerImg(file.id).then((res) => {
            if (res.message == "ok") {
              this.imgList = fileList
              this.form.pics = fileList
              this.$message({
                type: "success",
                message: "图片已删除!"
              });
            }
          })
        }).catch(() => {

        })
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleSuccess(res, file, fileList) {
        var newImg = {
          sell_id: this.form.id,
          uid: file.raw.uid,
          status: "success",
          url: "http://" + res.data.url,
        }
        addSellerImg(newImg).then((response) => {
          if (response.id) {
            newImg.id = response.id
            this.$message({
              type: "success",
              message: "添加新图片成功!"
            });
          }
        })
        this.form.pics.push(newImg)
        this.imgList.concat(newImg)
      },
      addMarker: function () {
        let lng = 121.5 + Math.round(Math.random() * 1000) / 10000;
        let lat = 31.197646 + Math.round(Math.random() * 500) / 10000;
        this.MakerPosition = [lng, lat];
      },
      onSearchResult(pois) {
        var self = this;
        let latSum = 0;
        let lngSum = 0;
        if (pois.length > 0) {
          pois.forEach(poi => {
            let { lng, lat } = poi;
            lngSum += lng;
            latSum += lat;
            this.MakerPosition = [poi.lng, poi.lat];
            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            });
            geocoder.getAddress([poi.lng, poi.lat], function (status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  self.addressInfo.traffic = result.regeocode.formattedAddress;
                  self.addressInfo.lat = poi.lat;
                  self.addressInfo.lng = poi.lng;
                  self.addressInfo.township = result.regeocode.addressComponent.township;
                  self.addressInfo.adcode =
                    result.regeocode.addressComponent.adcode;
                  self.addressInfo.position =
                    result.regeocode.addressComponent.city +
                    "-" +
                    result.regeocode.addressComponent.district;
                  self.address = result.regeocode.formattedAddress;
                  self.form.info[1].info = self.address
                  self.$nextTick();
                }
              }
            });
          });
          let center = {
            lng: lngSum / pois.length,
            lat: latSum / pois.length
          };
          this.center = [center.lng, center.lat];
        }
      },
      addType0() {
        this.$confirm("您确定要添加此项优惠?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.type0.description = "满" + this.type0.price + "减" + this.type0.discount
            this.type0.sell_id = this.form.id
            addSellerSupport(this.type0).then((res) => {

              if (res.message == "ok") {
                this.form.supports.push({
                  id: res.id,
                  description: this.type0.description,
                  type: 1
                });
                this.type0.price = 0;
                this.type0.description = "";
                this.type0.discount = 0;
                this.$message({
                  type: "success",
                  message: "添加成功!"
                });
              }
            })

          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消添加"
            });
          });
      },
      addType1() {
        this.$confirm("您确定要添加此项优惠?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.type1.description = "活动期间全场" + this.type1.discount + "折",
              this.type1.sell_id = this.form.id
            addSellerSupport(this.type1).then((res) => {
              if (res.message == "ok") {
                this.form.supports.push({
                  id: res.id,
                  description: this.type1.description,
                  type: 2
                });
                this.type1.discount = 9;
                this.type1.price = 0;
                this.type1.description = "";
                this.$message({
                  type: "success",
                  message: "添加成功!"
                });
              }
            })
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消添加"
            });
          });
      },
      addType2() {
        this.$confirm("您确定要添加此项优惠?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.type2.description = this.type2.description + "总共" + this.type2.price + "元",
              this.type2.sell_id = this.form.id
            addSellerSupport(this.type2).then((res) => {
              if (res.message == "ok") {
                this.form.supports.push({
                  id: res.id,
                  description: this.type2.description,
                  type: 3
                });
                this.type2.discount = 9;
                this.type2.price = 0;
                this.type2.description = "";
                this.$message({
                  type: "success",
                  message: "添加成功!"
                });
              }
            })
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消添加"
            });
          });
      },
      handleClose(id, index) {
        this.$confirm("您确定要删除此项优惠?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            delSellerSupport(id).then((res) => {
              if (res.message == "ok") {
                console.log(index)
                this.form.supports.splice(index, 1);
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
              }
            })

          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      saveInfo() {

        if (this.invoice == true) {
          this.form.invoice = 1
        }
        if (this.vip == true) {
          this.form.send = 1
        }
       
        var infos = this.form.info

        this.form.info = []
        this.form.pics = []
        this.form.supports = []

        updateSeller(this.form, this.addressInfo, infos).then((res) => {
          if (res.message == "ok") {
            this.$message({
              message: '更新成功',
              type: 'success'
            });
          }
        })

      },
      handleChange(value) {
        this.form.type = value[0]
        this.form.childType = value[1]
      }
    }
  };

</script>
<style>
  .amap-demo {
    height: 300px;
  }
  
  .search-box {
    position: absolute;
    top: 25px;
    left: 20px;
  }
  
  #user .el-vue-search-box-container {
    position: absolute;
  }
  
  .amap-page-container {
    position: relative;
    height: 360px;
  }
  
  .cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .cover-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .cover {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .w100 {
    width: 100px;
  }
  
  .w200 {
    width: 200px;
  }
  
  .p20 {
    padding: 20px 0;
  }
</style>